package ministock;

import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.code.ministock.ServiceProvider;
import com.google.code.ministock.Stock;
import com.google.code.ministock.impl.SinaServiceProvider;

public class CommentProducer extends Agent {
	
	private static final Logger logger = LoggerFactory.getLogger(CommentProducer.class);
	
	private volatile boolean workingTime;

	public CommentProducer(ConcurrentMap<String, List<Subscription>> map,
			BlockingQueue<Stock> stocks, boolean stopped) {
		super(map,stocks,stopped);
	}
	
	@Override
	public void run() {
		Timer timer = new Timer();
		long period = MiniStock.getCommentPeriod();
		logger.debug("Comment time period is {}", period);
		timer.scheduleAtFixedRate(new SubscriptionConsumer(), 1000, period);
		while (!stopped) {
			Calendar now = (Calendar) Calendar.getInstance(Locale.CHINA).clone();
			int hour = now.get(Calendar.HOUR_OF_DAY);
			workingTime = hour >= MiniStock.getOpenningHour() && hour <= MiniStock.getClosingHour();
		}
		timer.cancel();
	}
	
	private String[] getStockNames() {
		Set<String> keys = subscriptionsMap.keySet();
		logger.debug("{} stocks subscribed.{}", keys.size(), keys);
		return keys.toArray(new String[keys.size()]);
	}

	private class SubscriptionConsumer extends TimerTask {
		@Override
		public void run() {
			if (workingTime) {
				ServiceProvider sp = new SinaServiceProvider();
				String[] stockNames = getStockNames();
				if(stockNames.length > 0) {
					List<Stock> result = sp.query(stockNames);
					for(Stock stock : result) {
						try {
							stocks.put(stock);
							logger.info("{} information preparing...", stock.getDisplayName());
							logger.debug(CommentConsumer.displayStock(stock));
						} catch (InterruptedException e) {
							e.printStackTrace(System.out);
							break;
						}
					}
				}
			}
		}
	}
}
